﻿using CM.Resources.Web.Comm.Log;
using CM.Resources.Web.Core;
using CM.UserCenter.Common;
using Newtonsoft.Json;
using QL.Core;
using QL.Core.Log;
using QL.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CM.Resources.Web.Controllers
{
    //
    //http请求处理
    //
    public class HttpHandleController : BaseController
    {
        static private ILogger log = RYLogger.GetLogger("HttpHandleController");
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="File">文件</param>
        /// <param name="SiteName">站点</param>
        /// <returns></returns> 
        public JsonResult upload(FileData FileData)
        {
            //上传校验
            JsonResult JR = Validate(FileData.SiteName);
            if (JR != null) { return JR; }
            if (Request.Files.Count > 0)
            {

                var File = Request.Files[0];
                ReponseBean Rb = null;
                try
                {
                    //文件保存目录
                    string FullPath = FileHandler.getFilePath(GetRealPath(), FileData.SiteName);
                    //文件名
                    string FileName = FileHandler.getFileName(FileData.OrgFileName);
                    //文件路径
                    string FilePath = string.Format("{0}\\{1}", FullPath, FileName);
                    //保存文件
                    FileHandler.save(FilePath, File, FileData);
                    //返回客户端信息
                    Rb = getReponseBean(FullPath, FileData.SiteName, FileName);
                }
                catch (Exception e)
                {
                    log.Error(e, "上传文件");
                    Rb = new ReponseBean(ReponseCode.SERVER_ERROR, "文件服务器出错");
                }
                return Json(Rb, JsonRequestBehavior.AllowGet);
            }
            else {
                log.Error("上传文件失败:请求中没有文件流");
                return Json(new ReponseBean(ReponseCode.SERVER_ERROR, "请求中没有文件流"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 封装返回结果
        /// </summary>
        /// <param name="FullPath">文件完整路径</param>
        /// <param name="domain">文件储存二级目录</param>
        /// <returns></returns>
        private ReponseBean getReponseBean(string FullPath, string SiteName, string FileName)
        {
            log.Debug("FilePath-SiteName-FileName:{0}-{1}-{2}", FullPath, SiteName, FileName);
            string RegexStr = string.Format(@"{0}\\\S+", SiteName);
            Match mt = Regex.Match(FullPath, RegexStr);
            string path = FullPath.Replace(GetRealPath(), "").Replace("\\", "/");
            string Domain = Configuration.Default.Domain;
            return new ReponseBean(ReponseCode.SUCCESSED, string.Format("{0}{1}/{2}", Domain, path, FileName));
        }
        /// <summary>
        /// 获取虚拟路径对应的真实路径
        /// </summary>
        /// <returns></returns>
        private string GetRealPath()
        {
            return Utility.ToAbsolutePath(Configuration.Default.UploadDir);
        }
        /// <summary>
        /// 上传校验
        /// </summary>
        /// <param name="SiteName">站点名</param>
        /// <returns></returns>
        private JsonResult Validate(string SiteName)
        {
            bool SiteExists = Configuration.Default.SitesArray.Contains(SiteName);
            if (!Configuration.Default.AllowUpload)
            {
                log.Debug("未允许上传");
                return Json(new ReponseBean(ReponseCode.Not_Allow_Upload, "未允许上传"), JsonRequestBehavior.AllowGet);
            }
            else if (!FileHandler.ValidateRemoteIP())//IP校验
            {
                log.Debug(WebContext.Request.RemoteAddress + "IP校验失败");
                return Json(new ReponseBean(ReponseCode.Permission_Denied, "未授权访问"), JsonRequestBehavior.AllowGet);
            }
            else if (SiteName == null || SiteName == "" || (!SiteExists))//站点校验
            {
                log.Debug(SiteName + "站点不存在");
                return Json(new ReponseBean(ReponseCode.SITE_NOT_EXISTS, "站点不存在"), JsonRequestBehavior.AllowGet);
            }

            return null;
        }
    }
}